package com.nightpiter.controller.algorithms;

import android.os.Handler;

import com.nightpiter.controller.MetroController;
import com.nightpiter.controller.algorithms.exceptions.DijkstraException;
import com.nightpiter.controller.log.Logger;

/**
 * MetroRouterState class. Contains info about the current preparing phase of
 * the MetroRouter
 * 
 * @author Eldar Abusalimov (eldar.abusalimov@gmail.com)
 */
public class MetroRouterState implements Cloneable {

	/**
	 * Possible actions
	 * 
	 * @author Eldar Abusalimov (eldar.abusalimov@gmail.com)
	 */
	public enum Action {
		IDLE, PREPARING
	}

	/**
	 * the current action
	 */
	Action action = Action.IDLE;

	/**
	 * handler that would receive messages
	 */
	private Handler handler;

	/**
	 * true if the preparation is completed
	 */
	boolean readyProgress = true;

	/**
	 * current processing phase
	 */
	int pass = 0;

	/**
	 * if there was an error
	 */
	DijkstraException error = null;

	/**
	 * public constructor
	 */
	public MetroRouterState() {
	}

	/**
	 * post a message about state change to the handler
	 */
	void notifyHandler() {
		if (this.handler != null) {
			MetroRouterState state;
			try {
				state = (MetroRouterState) this.clone();
			} catch (CloneNotSupportedException e) {
				state = this;
			}
			this.handler.sendMessage(this.handler.obtainMessage(
					MetroController.MSG_ROUTER_STATE_CHANGED, state));
		} else {
			Logger.log("ERROR!!! Handler is not assigned!");
		}
	}

	/**
	 * set all progress field to false;
	 */
	void resetAll(Handler handler) {
		this.handler = handler;
		readyProgress = false;
		pass = 0;
		notifyHandler();
	}

	/**
	 * @return the action
	 */
	public Action getAction() {
		return action;
	}

	/**
	 * @param readyProgress
	 *            the readyProgress to set
	 */
	void setReady(boolean readyProgress) {
		this.readyProgress = readyProgress;
		notifyHandler();
	}

	/**
	 * @param pass
	 *            the pass to set
	 */
	void setPass(int pass) {
		this.pass = pass;
		notifyHandler();
	}

	/**
	 * @param error
	 *            the error to set
	 */
	void setError(DijkstraException error) {
		this.error = error;
		notifyHandler();
	}

	/**
	 * @return the error
	 */
	public DijkstraException getError() {
		return error;
	}

	/**
	 * @return the readyProgress
	 */
	public boolean isReady() {
		return readyProgress;
	}

	/**
	 * @return the pass
	 */
	public int getPass() {
		return pass;
	}

}
